package com.syzg.base.person.controller;

import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.syzg.base.aduit.config.AuditConfig;
import com.syzg.base.aduit.model.Audit;
import com.syzg.base.aduit.service.AuditService;
import com.syzg.base.login.model.LoginObject;
import com.syzg.base.merge.model.Person;
import com.syzg.base.merge.model.Role;
import com.syzg.base.person.service.PersonService;
import com.syzg.base.role.service.RoleService;
import com.syzg.common.config.SysProperties;
import com.syzg.common.controller.BaseController;
import com.syzg.common.controller.CustomDateEditor;
import com.syzg.common.exception.BaseException;
import com.syzg.common.model.WebInfo;
import com.syzg.common.model.WebObj;
import com.syzg.common.util.MethodUtil;
import com.syzg.common.util.PKCreator;
import com.syzg.common.util.SearchMap;
import com.syzg.core.page.PageResult;
import com.syzg.core.util.SecurityUtil;
import com.syzg.core.util.StringUtil;

@Controller
@RequestMapping("/path/person")
public class PersonController extends BaseController {

	static Logger log = LoggerFactory.getLogger(PersonController.class);

	@Resource
	private PersonService personService;
	@Resource
	private RoleService roleService;
	@Resource
	private AuditService auditService;

	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(true));
	}

	@RequestMapping("/listPerson")
	public ModelAndView listPerson(WebObj webObj) throws Exception {
		ModelAndView mv = new ModelAndView("/base/jsp/person/listPerson.jsp");
		SearchMap searchMap = SearchMap.forClass(Person.class);
		String title = webObj.getSearchValue().get("title");
		if (StringUtil.isNotEmpty(title)) {
			searchMap.like("a.name", "%" + title + "%");
		}
		PageResult pageResult = personService.findObjectsForPage(webObj.getPageNo(), SysProperties.PAGESIZE, searchMap);
		webObj.setPageResult(pageResult);
		mv.addObject("webObj", webObj);
		return mv;
	}

	@RequestMapping("/initPerson")
	public ModelAndView initPerson() throws Exception {
		ModelAndView mv = new ModelAndView("/base/jsp/person/addPerson.jsp");
		try {
			mv.addObject("person", new Person());
			mv.addObject("roleList", roleService.findRoles());
			/*
			 * LoginObject loginObj = SystemUtil.getLoginObject();
			 * this.person.setCreatePersonId(new
			 * String(loginObj.getPersonId()));
			 * this.person.setCreator(loginObj.getPersonName());
			 * this.person.setCreateTime(new Date());
			 */
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}

	@RequestMapping("/addPerson")
	public @ResponseBody String addPerson(Person person, String roleId, HttpServletRequest request) throws Exception {
		WebObj webObj = new WebObj();
		Audit audit = null;
		try {
			/*
			 * LoginObject loginObj = SystemUtil.getLoginObject();
			 * this.person.setCreatePersonId(new
			 * String(loginObj.getPersonId()));
			 * this.person.setCreator(loginObj.getPersonName());
			 * this.person.setCreateTime(new Date());
			 */
			person.setId(PKCreator.getPk());
			String[] roleIds = null;
			if (StringUtil.isNotEmpty(roleId)) {
				String[] strAry = roleId.split(",");
				roleIds = new String[strAry.length];
				for (int i = 0; i < strAry.length; i++) {
					roleIds[i] = strAry[i];
				}
			} else {
				roleIds = new String[0];
			}
			personService.createPerson(person, roleIds);
			audit = new Audit("添加用户[" + person.getAccount() + "]", AuditConfig.TYPE_INSERT, AuditConfig.OP_SUCCESS,
					request);
			setControllerStatus(webObj, WebInfo.STATUS_SUCCESS);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj, WebInfo.STATUS_FAILURE);
			webObj.getWebInfo().getErrorList().add("添加人员失败");
			audit = new Audit("添加用户[" + person.getAccount() + "]", AuditConfig.TYPE_INSERT, AuditConfig.OP_FAILURE,
					request);
		}
		auditService.create(audit);
		return new JSONObject(webObj).toString();
	}

	@RequestMapping("/viewPerson")
	public ModelAndView viewPerson(Person person, ModelAndView mv) throws Exception {
		mv.setViewName("/base/jsp/person/viewPerson.jsp");
		try {
			String id = person.getId();
			Person personVO = personService.findObjectById(id);
			mv.addObject("person", personVO);
			List<Role> lstRole = roleService.findRolesByPerson(id);
			mv.addObject("roleList", lstRole);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}

	@RequestMapping("/editPerson")
	public ModelAndView editPerson(String id) throws Exception {
		ModelAndView mv = new ModelAndView("/base/jsp/person/editPerson.jsp");

		try {
			Person person = personService.findObjectById(id);
			mv.addObject("person", person);
			List<Role> list = roleService.findRolesByPerson(id);
			mv.addObject("roleList", list);
			WebObj webObj = new WebObj();
			mv.addObject("webObj", webObj);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}

	@RequestMapping("/modPerson")
	public @ResponseBody String modPerson(String id, Person personVO, String roleId, HttpServletRequest request)
			throws Exception {
		WebObj webObj = new WebObj();
		Audit audit = null;
		try {
			Person person = personService.findObjectById(id);
			person = (Person) MethodUtil.copyProperties(person, personVO);
			String[] roleIds = null;
			if (StringUtil.isNotEmpty(roleId)) {
				String[] strAry = roleId.split(",");
				roleIds = new String[strAry.length];
				for (int i = 0; i < strAry.length; i++) {
					roleIds[i] = strAry[i];
				}
			} else {
				roleIds = new String[0];
			}
			personService.updatePerson(person, roleIds);
			setControllerStatus(webObj, WebInfo.STATUS_SUCCESS);
			audit = new Audit("修改用户[" + personVO.getAccount() + "]", AuditConfig.TYPE_UPDATE, AuditConfig.OP_SUCCESS,
					request);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj, WebInfo.STATUS_FAILURE);
			webObj.getWebInfo().getErrorList().add("修改人员信息失败");
			audit = new Audit("修改用户[" + personVO.getAccount() + "]", AuditConfig.TYPE_UPDATE, AuditConfig.OP_FAILURE,
					request);
		}
		auditService.create(audit);
		return new JSONObject(webObj).toString();
	}

	@RequestMapping("/delPerson")
	public ModelAndView delPerson(String id, WebObj webObj, HttpServletRequest request) throws Exception {
		String[] ids = webObj.getSelectedRow();
		String dels = "";
		Audit audit = null;
		try {
			if (ids == null) { // 删除单个
				if (id == null) {
					ids = new String[0];
				} else {
					ids = new String[] { String.valueOf(id) };
				}
			}
			String[] idsStr = new String[ids.length];
			int i = 0;

			for (String idVO : ids) {
				idsStr[i++] = new String(idVO);
				dels += personService.findObjectById(idVO).getAccount() + ",";
			}
			personService.deletePerson(idsStr);
			audit = new Audit("删除用户[" + dels + "]", AuditConfig.TYPE_DELETE, AuditConfig.OP_SUCCESS, request);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			audit = new Audit("删除用户[" + dels + "]", AuditConfig.TYPE_DELETE, AuditConfig.OP_FAILURE, request);
		}
		auditService.create(audit);
		return listPerson(webObj);
	}

	/**
	 * 转至修改密码页面
	 * @param defaultPassword 是否因为默认密码而强制更改
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toUpdatePassword")
	public ModelAndView toUpdatePassword(HttpServletRequest request) throws Exception {
		ModelAndView mv = new ModelAndView("/base/jsp/modifypassword/editPassword.jsp");
		try {
			LoginObject currentLogin = (LoginObject) request.getSession().getAttribute(SysProperties.LOGIN_OBJECT);
			mv.addObject("currentLogin",currentLogin);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mv;
	}

	/**
	 * 修改密码
	 * @param oldPassword 原密码
	 * @param newPassword 新密码
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updatePassword")
	@ResponseBody
	public String updatePassword(String oldPassword, String newPassword, HttpServletRequest request) throws Exception {
		//CSRFTokenManager.validateForm(request);
		String result = "success";
		try {
			LoginObject currentLogin = (LoginObject) request.getSession().getAttribute(SysProperties.LOGIN_OBJECT);
			//检测原密码是否正确
			String personId = currentLogin.getPersonId();
			Person person = personService.findObjectById(personId);
			if(currentLogin.isDefaultPassword()){
				oldPassword = SysProperties.DEFAULT_PASSWORD;
			}
			if(!person.getPassword().equals(SecurityUtil.md5Hex(oldPassword)))
			{
				return "OLD_PASSWORD_ERROR";
			}
			personService.updatePassword(currentLogin.getPersonId(), oldPassword, newPassword);
			//刷新session
			currentLogin.setDefaultPassword(false);
			request.getSession().setAttribute(SysProperties.LOGIN_OBJECT,currentLogin);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result = "faile";
		}
		return result;
	}
	/**
	 * 重置密码
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/resetPassword")
	@ResponseBody
	public String resetPassword(String personId) throws Exception {
		String result = "success";
		try {
			Person person = personService.findObjectById(personId);
			//设置默认密码
			person.setPassword(SysProperties.DEFAULT_PASSWORD);
			personService.updatePerson(person);;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result = "faile";
		}
		return result;
	}
}
